package com.mec.web.y2012.coreservlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.mec.beans.y2012.coreservlet.Catalog;
import com.mec.beans.y2012.coreservlet.CatalogItem;

public abstract class CatalogPageServlet extends HttpServlet {
	private static final long serialVersionUID = -4829162119583482254L;
	
	private CatalogItem[] items;
	private String[] itemsId;
	private String title;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		if(null == items){
			resp.sendError(resp.SC_NOT_FOUND, "Missing Items");
			return;
		}
		
		//
		resp.setContentType("text/html");
		PrintWriter out = resp.getWriter();
		//
		out.println(
				Constants.docType + ServletUtilities.headWithTitle(title) +
				"<body><h1>" + title + "</h1>"
				);
		for(int i = 0 ; i < items.length ; ++i){
			CatalogItem item = items[i];
			out.println("<hr/>");
			if(null == item){
				out.println("<strong>Unknown item id : " + itemsId[i]);
			}else{
				String formURL = "OrderPageServlet";
				formURL = resp.encodeURL(formURL);
				//
				out.println("<form action=\"" + formURL + "\">" +
						"<input type=\"hidden\" name=\"itemId\" value=\"" + item.getItemId() + "\"/>" +
						"<h2>" + item.getShortDescription() + "($" + item.getCost() + ")</h2>" + item.getLongDescription() +
						"<input type=\"submit\" value=\"Add to Shopping Cart\"/></form>"
						);
			}
		}
		//
		out.println("<hr/></body></html>");
	}

	protected void setItems(String[] itemsId){
		this.itemsId = itemsId;
		items = new CatalogItem[itemsId.length];
		for(int i = 0 ; i < items.length ; ++i){
			items[i] = Catalog.getItem(itemsId[i]);
		}
	}

	protected void setTitle(String title){
		this.title = title;
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}


	private static final Logger logger = 
			Logger.getLogger(CatalogPageServlet.class);
}
